import { isUrl } from '@ant-design/pro-components';
import { addToken } from './authentication';
import { cqrs } from './cqrs';
import authorizedMenus from '@sfkj/sfw-dc-ui/utils/umi/authorizedMenus';
import { MappingAlgorithm, theme } from 'antd';
import lodash from 'lodash';
import ddeRender from '@sfkj/sfw-dc-ui/DynamicComponent/ddeRender';

export function aopUrl(url: string) {
  if (!isUrl(url)) {
    return url;
  }
  if (url.indexOf('shanfe.cn') !== -1) {
    return addToken(url);
  }

  return url;
}

export function aopImageUrl(url: string) {
  if (!isUrl(url)) {
    return url;
  }
  return url;
}

/**
 * 转换为微应用Url，例如： /company/company-manage 在独立子应用用会处理为 /company-manage
 * @param url
 */
export function toMicroAppUrl(url: string) {
  if (window['__POWERED_BY_QIANKUN__'] !== true) {
    return url;
  }
  // "/company/company-manage".substring("/company/company-manage".indexOf('/', 1), "/company/company-manage".length)
  return url.substring(url.indexOf('/', 1), url.length);
  // return url;
}

export function pageReload(navigate: any, location: any) {
  navigate(`${location.pathname}${location.search}${location.hash}`, {
    replace: true,
  });
}

export async function downloadFile(path: string) {
  const result = await cqrs.queryForForm({
    body: {
      code: 'OssSignatureDownloadUrlQry',
      params: {
        data: {
          path,
        },
      },
    },
  });

  if (result.error) {
    return result;
  }

  const a = document.createElement('a');
  a.style.display = 'none';
  a.href = `${result.url}`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  return result;
}

const algorithmFunc = (algorithm: string[] | null): MappingAlgorithm[] | null => {
  const algorithmFuncs = [];
  if (lodash.indexOf(algorithm, 'dark') !== -1) {
    algorithmFuncs.push(theme.darkAlgorithm);
  }
  if (lodash.indexOf(algorithm, 'compact') !== -1) {
    algorithmFuncs.push(theme.compactAlgorithm);
  }
  return lodash.isEmpty(algorithmFuncs) ? null : algorithmFuncs;
}

export const aopUtils = {
  aopUrl,
  aopImageUrl,
  toMicroAppUrl,
  pageReload,
  downloadFile,
  authorizedMenus,
  algorithmFunc,
  ddeRender,
};
